var mongoose = require('mongoose');
var models = require('../db/models');
var config = require('../config/config');

var Schema = mongoose.Schema;
global.db=mongoose.connect(config.DB);


//初始化数据库表
for (var m in models) {
    mongoose.model(m, new Schema(models[m]));
}



//todo:node中moudle.exports和export的区别
//Todo:数据库连接断开，和释放的方法
//封装数据库连接操作
module.exports = {
    getModel: function (type) {
        return _getModel(type);
    }
};
var _getModel = function (type) {
    return mongoose.model(type);
};
//todo:还要写出来CRUD和数据库关闭，连接的方法

//mongodb连接监视
mongoose.connection.on('connected',function(){
    console.info("mongoose contected to"+config.DB);
});

mongoose.connection.on('error',function(err){
    console.info("mongoose contection error"+err);
});

mongoose.connection.on('disconnected',function(){
    console.info(config.DB+" mongoose disconnected");
});

process.on('SIGINT', function () {
    mongoose.connection.close(function () {
        console.info("mongoose disconnected through app termination");
        process.exit(0);
    });
});


